package com.lyl.mysqlmonitor.util;

import java.util.regex.Pattern;

/**
 * SQL模式匹配工具类
 * 集中管理所有与SQL相关的正则表达式
 */
public class SqlPatterns {
    
    // SQL类型判断的正则表达式
    public static final Pattern SELECT_PATTERN = Pattern.compile(
            "^\\s*SELECT\\s+.*$", 
            Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE);

    // 简单测试SQL模式
    public static final Pattern SELECT_1_FROM_DUAL = Pattern.compile(
            "^\\s*SELECT\\s+1\\s+FROM\\s+DUAL\\s*$", 
            Pattern.CASE_INSENSITIVE);
    
    public static final Pattern SELECT_1 = Pattern.compile(
            "^\\s*SELECT\\s+1\\s*$", 
            Pattern.CASE_INSENSITIVE);
    
    public static final Pattern SELECT_STAR_FROM_DUAL = Pattern.compile(
            "^\\s*SELECT\\s+\\*\\s+FROM\\s+DUAL\\s*$", 
            Pattern.CASE_INSENSITIVE);

    // MySQL 8.0特有语法检测模式
    public static final Pattern WITH_PATTERN = Pattern.compile(
            "^\\s*WITH\\s+.+?\\s+AS\\s+\\(.+?\\)\\s+SELECT",
            Pattern.CASE_INSENSITIVE);
    
    public static final Pattern WINDOW_FUNCTION_PATTERN = Pattern.compile(
            "\\bOVER\\s*\\([^)]*\\)",
            Pattern.CASE_INSENSITIVE);
    
    public static final Pattern JSON_TABLE_PATTERN = Pattern.compile(
            "\\bJSON_TABLE\\s*\\(",
            Pattern.CASE_INSENSITIVE);
    
    /**
     * 检查SQL是否为简单测试SQL
     * 
     * @param sql 要检查的SQL语句
     * @return 如果是简单测试SQL返回true，否则返回false
     */
    public static boolean isSimpleTestSql(String sql) {
        return SELECT_1_FROM_DUAL.matcher(sql).matches() 
                || SELECT_1.matcher(sql).matches() 
                || SELECT_STAR_FROM_DUAL.matcher(sql).matches();
    }
    
    /**
     * 检查SQL是否为SELECT语句
     * 
     * @param sql 要检查的SQL语句
     * @return 如果是SELECT语句返回true，否则返回false
     */
    public static boolean isSelectStatement(String sql) {
        return SELECT_PATTERN.matcher(sql).find();
    }
    
    /**
     * 检查SQL是否包含MySQL 8.0特有特性
     * 
     * @param sql 要检查的SQL语句
     * @return 如果包含MySQL 8.0特有特性返回true，否则返回false
     */
    public static boolean containsMySQL80Feature(String sql) {
        return WITH_PATTERN.matcher(sql).find()
                || WINDOW_FUNCTION_PATTERN.matcher(sql).find()
                || JSON_TABLE_PATTERN.matcher(sql).find();
    }
    
    /**
     * 私有构造函数，防止实例化
     */
    private SqlPatterns() {
        // 工具类不应被实例化
    }
} 